package com.jthinker.blog.web.controller.admin.login;

import com.jthinker.blog.bean.vo.Constant;
import com.jthinker.blog.bean.vo.UserWrapper;
import com.jthinker.blog.service.UserInfoService;
import com.jthinker.blog.util.RSAUtils;
import com.jthinker.blog.web.controller.admin.common.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * User: Gang Chen
 * Date: 2015/8/4 19:23
 */
@Controller
public class LoginController extends BaseController
{
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private UserInfoService userInfoService;

    @RequestMapping(value = Constant.URL_LOGIN, method = RequestMethod.GET)
    public String view()
    {
        return "login/login";
    }

    @RequestMapping(value = Constant.URL_LOGIN, method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> login(HttpServletRequest request, String username, String password)
    {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password))
        {
            return getErrorMessage("用户名密码不能为空!");
        }

        String rawPass = RSAUtils.decryptStringByJs(password);

        UserWrapper user = userInfoService.login(username, rawPass, request);

        if (user == null)
        {
            return getErrorMessage("用户名或密码错误!");
        }
        else
        {
            return getSuccessMessage("登录成功!");
        }
    }

    @RequestMapping(value = Constant.URL_LOGOUT, method = { RequestMethod.POST, RequestMethod.GET })
    public String logout(HttpServletRequest request)
    {
        userInfoService.logout(request);
        return "redirect:/";
    }

}
